package com.boxin.ims.modules.wechat.busi;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.boxin.framework.base.utils.DateUtils;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.service.WechatMemberService;

/**
 * @author Jakemanse
 * @date 2013-11-5
 * @function <p>生日处理 </p>
 */
@Service
public class BirthdayProcessor extends BusinessProcessor{
	
	private static Map<String,Integer> counterMap = new HashMap<String,Integer>();

	@Autowired
	private WechatMemberService wechatMemberService;
	public BirthdayProcessor() {
		super();
	}

	@Override
	public ProcessMessage process() {
		
		WechatMember member = memberCheckAndReply();
		String reply ="";
		if(member != null){
			String keywords = textMessage.getContent();
			keywords = keywords.replaceAll("我的生日", "");
			
			//更新计数
			String today  = DateUtils.getTodayString();
			String key = today + member.getId();
			Integer counter = counterMap.get(key);
			if(counter != null && counter>=2){
				reply ="亲,您已超过当天允许最大修改生日日期次数,请于明天再重新更改，谢谢！";
				writeToUser(reply);
				return null;
			}
			
			String regex = "(^[1,2]\\d{7})$";
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher =  pattern.matcher(keywords);
			if(matcher.matches()){
				String birthday = matcher.group(1);
				member.setBirthday(birthday);
				wechatMemberService.save(member);
				//更新计数
				counter =(counter==null) ? 0: counter+1;
				counterMap.put(key, counter);
				
				reply = "亲爱的微会员,您的生日日期已更新为【"+member.getBirthday()+"】,谢谢！";
				writeToUser(reply);
				return null;
			}else{
				reply = "您输入的格式不正确,请重新验证后再输入,如:我的生日19880808,不要添加额外信息，否则系统无法识别您的生日日期，谢谢!";
				writeToUser(reply);
			}
		}
		
		return null;
	}

	@Override
	public boolean isNeedBeMember() {
		return false;
	}
	
	
}
